package cn.springcloud.fix.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Optional;

/**
 * 路由限流配置
 */
@Configuration
public class RateLimiterConfig {

    /**
     * 按照Path限流(采用这个)
     * http://www.itmuch.com/spring-cloud-gateway/spring-cloud-rate-limit/
     */
    @Bean(value = "pathKeyResolver")
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 针对用户的限流：
     */
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(
                Optional.ofNullable(exchange.getRequest().getQueryParams().getFirst("user")).orElse("")
        );
    }

    /**
     * 针对来源IP的限流：
     */
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(
                Optional.ofNullable(exchange.getRequest().getHeaders().getFirst("X-Forwarded-For")).orElse("")
        );
    }

    /**
     * ip地址限流
     */
    public KeyResolver addressResolver() {
        return exchange -> Mono.just(
                Optional.ofNullable(exchange.getRequest().getRemoteAddress()).map(InetSocketAddress::getAddress).map(InetAddress::getHostAddress).orElse("")
        );
    }

    /**
     * hostName限流
     */
    public KeyResolver hostNameResolver() {
        return exchange -> Mono.just(
                Optional.ofNullable(exchange.getRequest().getRemoteAddress()).map(InetSocketAddress::getHostName).orElse("")
        );
    }
}
